package biz

import (
	"encoding/base64"
	"github.com/obs-data-process/internal/biz/domain"
	"github.com/obs-data-process/internal/data/obs"
	"github.com/pkg/errors"
)

type ImageRepo interface {
	LoadAll(filename string) ([]*domain.Image, error)
}

type ImageUserCase struct {
	cli *obs.ObsClient
	repo ImageRepo
}

func NewImageUserCase(cli *obs.ObsClient, repo ImageRepo) *ImageUserCase {
	return &ImageUserCase{cli: cli, repo: repo}
}


func (uc *ImageUserCase) GetImages(filename string) ([]*domain.Image,error)  {
	 return uc.repo.LoadAll(filename)
}

func ( uc *ImageUserCase) GetTempSignatureUrl(bucket, key, processCommand, newObjectName string) (string, error) {
	var params = make(map[string]string)
	params["x-image-process"] = processCommand
	params["x-image-save-object"] = base64.StdEncoding.EncodeToString([]byte(newObjectName))
	var req = &obs.CreateSignedUrlInput{
		Method:      obs.HttpMethodGet,
		Bucket:      bucket,
		Key:         key,
		QueryParams: params,
	}

	res, err := uc.cli.CreateSignedUrl(req)
	//log.Printf("create signed url resp: %+v", res)
	if err != nil {
		return "", errors.Wrap(err, "do CreateSignedUrl failed")
	}
	output, err := uc.cli.GetObjectWithSignedUrl(res.SignedUrl, res.ActualSignedRequestHeaders)
	if err != nil {
		return "", errors.Wrapf(err, "do GetObjectWithSignedUrl failed, process command: %s", processCommand)
	}
	//log.Printf("GetObjectWithSignedUrl resp: %+v", output)
	defer output.Body.Close()
	return res.SignedUrl,nil
}
